//
//  DEWAddressListController.m
//  OtherDemo
//
//  Created by lianjie on 2018/7/25.
//  Copyright © 2018年 lianjie. All rights reserved.
//

#import "DEWAddressListController.h"
#import "DEWAddressTableCell.h"
#import "DEWMessageToolsTableCell.h"
#import "pinyin.h"
#import "DELBMChineseSort.h"
@interface DEWAddressListController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic ,strong) UITableView *table;

///
@property (nonatomic ,strong) NSMutableDictionary *dataDic;

///
//@property (nonatomic ,strong) NSMutableDictionary *<#name#>;

///
@property (nonatomic ,strong) NSMutableArray *friendList;

///保存字母
@property (nonatomic ,strong) NSMutableArray *sectionIndexArray;

@end

@implementation DEWAddressListController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"通讯录";
    
    _dataDic = [NSMutableDictionary dictionary];
//    _friendList = [NSMutableArray array];
    _sectionIndexArray = [NSMutableArray array];
    
    [self loadData];
    [self createView];
    
}
#pragma mark ----requestData
-(void)loadData
{
    weakSelf(weakSelf);
    
    NSMutableDictionary *pramseDic = [NSMutableDictionary dictionary];
    DELoginModel *model = [HHUserManager getUserInfo];
    [pramseDic setObject:model.userId forKey:@"userId"];
    [pramseDic setObject:model.tokenId forKey:@"tokenId"];
    NSString *url = [KSService addressBookListAPI];
    [KSHTTPSTool post:url params:pramseDic success:^(id responseObject) {
        if (DERetCode) {
            NSArray *arr = responseObject[@"data"];
            
            if (arr.count>0) {
                [weakSelf doDataListWithArr:arr];
            }
            
            [weakSelf.table reloadData];
        }else{
            [[AlertHelper sharedManager]alertWithMessage:[NSString stringWithFormat:@"%@",responseObject[@"retMsg"]]];
        }
    } failure:^(NSError *error) {
        [weakSelf showHint:@"系统异常，稍后再试！"];
    }];
    
    
    
    
//    NSArray *arr = @[@"lala",@"yaya",@"aoao",@"tutu",@"pipi",@"azi",@"weiwei",@"mumu"];
//
//    [self doDataListWithArr:arr];
    
    
}
///处理数据
- (void)doDataListWithArr:(NSArray *)arr
{
    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *name = obj[@"pinyin"];
        NSString *perfix = [[name substringToIndex:1] uppercaseString];
        if (![self->_sectionIndexArray containsObject:perfix]) {
            [self->_sectionIndexArray addObject:perfix];
        }
    }];
    
    for (NSString *perfix in _sectionIndexArray) {
        
        NSMutableArray *nameArray = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            
            NSString *cityNameEN = dic[@"pinyin"];///拼音
            if ([cityNameEN hasPrefix:[perfix lowercaseString]] || [cityNameEN hasPrefix:[perfix uppercaseString]]) {
                [nameArray addObject:dic];
            }
            
        }
        [_dataDic setObject:nameArray forKey:perfix];
    }
    ///排序
    _sectionIndexArray = [NSMutableArray arrayWithArray:[_sectionIndexArray sortedArrayUsingSelector:@selector(compare:)]];
}

#pragma mark ---initView
-(void)createView
{
    [self.view addSubview:self.table];
    
    
}
#pragma mark ---tableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionIndexArray.count+1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return [self.dataDic[self.sectionIndexArray[section-1]] count];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    DEWMessageToolsTableCell *cell = [[DEWMessageToolsTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    if (section == 0) {
        
        cell.titleLab.text = @"我的群聊";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.imageV.backgroundColor = CellLineColor;
        cell.imageV.image = [UIImage imageNamed:@"LJ群聊"];
        
        cell.lj_lineWith = 0;
        
    }else{
        
        cell.titleLab.font = [UIFont systemFontOfSize:16.0f];
        
        NSDictionary *dic = self.dataDic[self.sectionIndexArray[indexPath.section-1]][indexPath.row];
        
        cell.titleLab.text = dic[@"nickName"];
        
        cell.imageV.backgroundColor = CellLineColor;
        [cell.imageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",SERVER_URLIMAGE,dic[@"avatarUri"]]] placeholderImage:kDefalutUserHeader];
        
    }
    
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75.0f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20.0f;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (indexPath.section == 0) {
        ///我的群聊
        BaseViewController *vc = [[NSClassFromString(@"DEWMyGroupChatController") alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        ///好友
        
    }
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
        return nil;
    }else{
        UIView *view = [UIView new];
        view.frame = CGRectMake(0, 0, DEWScreenWidth, 20.0f);
        view.backgroundColor = [UIColor clearColor];
        
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(10.0f, 0, 100, 20.0f)];
        lab.font = [UIFont systemFontOfSize:14.0f];
        
        lab.textColor = UIColorFromRGB(0x999999);
        
        lab.text = self.sectionIndexArray[section-1];
        
        [view addSubview:lab];
        
        
        return view;
    }
    
}

//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//
//}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    
    return self.sectionIndexArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    [self showHint:title];
    //    NSLog(@"%@---%ld", title, index);
    // 显示正在点击的indexTitle ZJProgressHUD这个小框架是我们已经实现的
//    [ZJProgressHUD showStatus:title andAutoHideAfterTime:0.5];
    return index;
}

#pragma mark --lazy
-(UITableView *)table
{
    if (!_table) {
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEWScreenWidth, DEWScreenHeight-(NAVH)) style:UITableViewStyleGrouped];
        
        _table.delegate = self;
        
        _table.dataSource = self;
        
        _table.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _table;
    
}

-(NSMutableArray *)friendList
{
    if (!_friendList) {
        _friendList = [NSMutableArray array];
    }
    return _friendList;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
